package main

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math/rand"
	"net/http"
	"time"
)

func main() {
	r := gin.Default()

	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}
	//新增中间件
	r.Use(func(c *gin.Context) {
		s := time.Now()
		c.Next()
		fields := []zap.Field{
			zap.String("path", c.Request.URL.Path),
			zap.Int("status", c.Writer.Status()),
			zap.Duration("elapsed", time.Now().Sub(s)),
		}

		if value, exists := c.Get("requestId"); exists {
			fields = append(fields, zap.Int("requestId", value.(int)))
		}

		logger.Info("incoming request", fields...)
	}, func(c *gin.Context) {
		c.Set("requestId", rand.Int())
		c.Next()
	})

	r.GET("/ping", func(c *gin.Context) {

		h := gin.H{
			"message": "pong",
		}
		if value, exists := c.Get("requestId"); exists {
			h["requestId"] = value
		}
		c.JSON(http.StatusOK, h)
	})
	r.GET("/hello", func(context *gin.Context) {
		context.String(200, "hello")
	})
	r.Run(":9999") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
